package com.bluegalaxy.nhb.snservice.service.ck.impl;

import com.alibaba.fastjson.JSONObject;
import com.bluegalaxy.nhb.service.AssembleService;
import com.bluegalaxy.nhb.snservice.common.utils.DateUtil;
import com.bluegalaxy.nhb.snservice.common.utils.SqlTableUtil;
import com.bluegalaxy.nhb.snservice.common.utils.StringUtil;
import com.bluegalaxy.nhb.snservice.dao.FunnelMapper;
import com.bluegalaxy.nhb.snservice.dao.KeepMapper;
import com.bluegalaxy.nhb.snservice.dao.UserGroupMapper;
import com.bluegalaxy.nhb.snservice.domain.constant.CkConstant;
import com.bluegalaxy.nhb.snservice.domain.enums.BaseUserEnum;
import com.bluegalaxy.nhb.snservice.domain.vo.BootstrapTablePage;
import com.bluegalaxy.nhb.snservice.domain.vo.api.R;
import com.bluegalaxy.nhb.snservice.domain.vo.api.ck.FunnelParamVO;
import com.bluegalaxy.nhb.snservice.domain.vo.api.ck.KeepParamVO;
import com.bluegalaxy.nhb.snservice.service.ck.UserGroupService;
import com.bluegalaxy.nhb.snservice.service.execute.ExecuteService;
import com.bluegalaxy.nhb.snservice.service.execute.XxService;
//import com.bluegalaxy.nhb.sql.AssembleSql;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.dialect.helper.MySqlDialect;
import com.github.pagehelper.page.PageAutoDialect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("UserGroupService")
public class UserGroupServiceImpl implements UserGroupService {
    @Autowired
    private UserGroupMapper userGroupMapper;
    @Autowired
    private KeepMapper keepMapper;
    @Autowired
    private FunnelMapper funnelMapper;
    @Autowired
    private ExecuteService executeService;
    @Autowired
    private XxService xxService;

//    @Autowired
    @Resource
    private AssembleService assembleService;


    @Override
    public int insertBatch(String tableName, List<String> list) {
        return userGroupMapper.insertBatch(tableName,list,"");
    }

    @Override
    public R findUsersById(JSONObject param) {
        String tableId = param.getString("tableId");
        if (StringUtil.isEmpty(tableId)){
            return R.fail("");
        }
        String tableDate = param.getString("tableDate");

        int current = param.getInteger("current")==null? 0 :param.getInteger("current");
        int pageSize = param.getInteger("pageSize")==null? 10 :param.getInteger("pageSize");
//        current = current == 1?0:current;
        int startPage = current == 0?0:(current - 1) * pageSize;

        List<Map<String,Object>> alist = null;
        String tenantId = param.getString("lesseeId");
        if (StringUtil.isEmpty(tenantId)){
            alist = xxService.selectUserAttribute();
        }else {
            alist = xxService.selectUserAttribute(tenantId);
        }

//        List<Map<String, Object>> attrList = alist.stream()
//                .filter(map -> map.keySet().stream().noneMatch(key -> key == null || key.isEmpty()))
//                .collect(Collectors.toList());
        List<Map<String, Object>> attrList = alist.stream()
                .filter(map -> map.values().stream().noneMatch(value -> value == null || (value instanceof String && ((String) value).isEmpty())))
                .collect(Collectors.toList());
//        PageAutoDialect.registerDialectAlias("clickhouse", MySqlDialect.class);
        PageHelper.startPage(current,pageSize);
        List<Map<String,Object>> list = userGroupMapper.selectByTableName(tableId,tableDate,startPage,pageSize,attrList);
        Integer totalCount = 0;
        if (StringUtil.isEmpty(tableDate)){
            totalCount = userGroupMapper.countByTableName(tableId);
        }else{
            totalCount = userGroupMapper.countByDt(tableId,tableDate);
        }

//        PageInfo<Map<String,Object>> pageInfo = new PageInfo<>(list);
        BootstrapTablePage tablePage = new BootstrapTablePage();
        tablePage.setRows(list);
        tablePage.setTotal(totalCount.longValue());
        return R.data(tablePage);
    }

    @Override
    public R createUsers(JSONObject param) {
        String tableName = StringUtil.isEmpty(param.getString("tableId"))?SqlTableUtil.getGroupName():param.getString("tableId");
        String tableType = StringUtil.isEmpty(param.getString("tableType"))?"ADD":param.getString("tableType");
        String dt = StringUtil.isEmpty(param.getString("dt"))? DateUtil.getNowYYYYMMDD() :param.getString("dt");
        if ("ADD".equals(tableType)){
            boolean flag = executeService.createTable(tableName,BaseUserEnum.GROUP.name());
            if (!flag){
                return R.fail("创建分群错误");
            }
        }
        int dtCount = userGroupMapper.countByDt(tableName,dt);
        if (dtCount > 0){
            return R.fail("该日期【"+dt+"】下用户数据已存在。");
        }
        String sql = assembleService.assembleSql(param, CkConstant.ARRAY);
//        String sql = AssembleSql.assembleSql(param, CkConstant.ARRAY);
        List<String> list = userGroupMapper.selectBySql(sql);
        if (!list.isEmpty()){
            userGroupMapper.insertBatch(tableName,list,dt);
        }

        return R.data(list.size());
    }

    @Override
    public R createUsersByKeep(KeepParamVO paramVO) {
        String tableName = SqlTableUtil.getGroupName();
        List<Map<String,Object>> uList = keepMapper.selectKeepUserList(paramVO);
        if (uList.isEmpty()){
            return R.fail("分群用户为0");
        }
        boolean flag = executeService.createTable(tableName,BaseUserEnum.GROUP.name());
        if (!flag){
            return R.fail("创建分群错误");
        }

        List<String> dataList = uList.stream()
                .map(m -> m.getOrDefault("distinct_id","").toString())
                .collect(Collectors.toList());

        userGroupMapper.insertBatch(tableName,dataList,"");

        return R.status(true);
    }

    @Override
    public R createUsersByFunnel(FunnelParamVO paramVO) {
        String tableName = SqlTableUtil.getGroupName();
        List<Map<String,Object>> uList = funnelMapper.selectFunnelUser(paramVO);
        if (uList.isEmpty()){
            return R.fail("分群用户为0");
        }
        boolean flag = executeService.createTable(tableName, BaseUserEnum.GROUP.name());
        if (!flag){
            return R.fail("创建分群错误");
        }

        List<String> dataList = uList.stream()
                .map(m -> m.getOrDefault("distinct_id","").toString())
                .collect(Collectors.toList());

        userGroupMapper.insertBatch(tableName,dataList,"");

        return R.status(true);
    }

    @Override
    public R countUsers(JSONObject param) {
        String sql = assembleService.assembleSql(param, CkConstant.COUNT);
        int result = userGroupMapper.countBySql(sql);
        return R.data(result);
    }

    @Override
    public R selectUsers(JSONObject param) {
        String sql = assembleService.assembleSql(param, CkConstant.ARRAY);
        List<String> result = userGroupMapper.selectBySql(sql);
        return null;
    }
}
